﻿using System.Text;

namespace msilgc.cbuilder.CSyntaxTree
{
    internal class AssignToLocalVariable : ICStatementWithAssignment {
        public IVariable Target { get; set; }
        public IVariable Source { get; set; }
        public bool OnStack { get; set; }
        public bool DereferenceSourcePointer { get; set; }
        public bool DereferenceTargetPointer { get; set; }
        public string ExplicitSourceCast { get; set; }

        public AssignToLocalVariable(IVariable source, IVariable target) {
            Source = source;
            Target = target;
            OnStack = true;
            DereferenceSourcePointer = false;
            DereferenceTargetPointer = false;
            ExplicitSourceCast = string.Empty;
        }

        public void Emit(StringBuilder builder) {
            if(DereferenceTargetPointer)
            {
                builder.Append("*");
            }
            Target.Emit(builder);
            builder.Append(" = ");
            if (!string.IsNullOrEmpty(ExplicitSourceCast)) {
                builder.Append("(");
                builder.Append(ExplicitSourceCast);
                builder.Append(")");
            }
            if(DereferenceSourcePointer)
            {
                builder.Append("*");
            }
            Source.Emit(builder);
            builder.AppendLine(";");
        }
    }
}